import { useEffect, useCallback, useMemo, useRef } from "react";
import type { ActionType } from "@ant-design/pro-components";
import type { FormInstance } from "antd";
import usePcTable from "../../PcTable/hooks/usePcTable";
import usePcForm from "../../PcForm/hooks/usePcForm";
import type { PcPageConfig, ExtendedActionType } from "../types";

interface UsePcPageOptions<T, P> {
  /** 默认分页大小 */
  defaultPageSize?: number;
  /** 创建记录的模板 */
  createRecordTemplate?: () => T;
  /** 保存回调 */
  onSave?: (key: React.Key, row: T) => Promise<boolean>;
  /** 搜索提交回调 */
  onSearch?: (values: P) => Promise<void>;
  /** 搜索重置回调 */
  onReset?: () => void;
  /** 初始化时是否自动搜索 */
  autoSearch?: boolean;
  /** 是否在重置后自动搜索 */
  searchAfterReset?: boolean;
}

/**
 * PC端页面的自定义Hook
 * @template T - 数据类型
 * @template P - 搜索参数类型
 */
const usePcPage = <
  T extends Record<string, any>,
  P extends Record<string, any>
>(
  options: UsePcPageOptions<T, P>
) => {
  const {
    defaultPageSize = 10,
    createRecordTemplate,
    onSave,
    onSearch,
    onReset,
    autoSearch = true,
    searchAfterReset = true,
  } = options;

  // 使用表格 hook
  const {
    tableConfig,
    actionRef,
    formRef,
    dataSource,
    loading,
    pagination: tablePagination,
    setTableLoading,
    updateDataSource,
    setEditableRowKeys,
  } = usePcTable<T>({
    defaultPageSize,
    createRecordTemplate,
    onSave,
  });

  // 使用表单 hook
  const { formConfig, handleFinish, handleReset: baseHandleReset } = usePcForm<P>({
    onSearch,
    onReset,
  });

  // 创建稳定的引用
  const stableRef = useRef({
    handleFinish,
    baseHandleReset,
    setTableLoading,
    updateDataSource,
    setEditableRowKeys,
    searchAfterReset,
  });

  // 更新稳定引用
  useEffect(() => {
    stableRef.current = {
      handleFinish,
      baseHandleReset,
      setTableLoading,
      updateDataSource,
      setEditableRowKeys,
      searchAfterReset,
    };
  });

  // 处理搜索
  const handleSearch = useCallback(async (values: P) => {
    try {
      stableRef.current.setTableLoading(true);
      await stableRef.current.handleFinish(values);
    } finally {
      stableRef.current.setTableLoading(false);
    }
  }, []);

  // 处理重置
  const handleReset = useCallback(() => {
    stableRef.current.baseHandleReset();
    stableRef.current.setEditableRowKeys([]);
    if (stableRef.current.searchAfterReset) {
      handleSearch({} as P);
    }
  }, [handleSearch]);

  // 处理分页变化
  const handlePaginationChange = useCallback((current: number, pageSize: number) => {
    const values = formRef.current?.getFieldsValue() as P || {};
    handleSearch({ ...values, current, pageSize } as P);
  }, [handleSearch]);

  // 处理取消编辑
  const handleCancel = useCallback((key: React.Key) => {
    const record = dataSource.find(item => item.id === key);
    if (record?.id.toString().startsWith('temp_')) {
      // 如果是新增的临时记录，从数据源中移除
      stableRef.current.updateDataSource(
        dataSource.filter(item => item.id !== key),
        tablePagination.total
      );
    }
    stableRef.current.setEditableRowKeys([]);
  }, [dataSource, tablePagination.total]);

  // 合并分页配置
  const pagination = useMemo(() => ({
    ...tablePagination,
    onChange: handlePaginationChange
  }), [tablePagination, handlePaginationChange]);

  // 创建页面操作引用
  const pageActionRef = useRef<ExtendedActionType<P, T>>();

  // 更新页面操作引用
  useEffect(() => {
    pageActionRef.current = {
      reload: async (resetPageIndex?: boolean) => {
        if (resetPageIndex) {
          const values = formRef.current?.getFieldsValue() as P || {};
          await handleSearch({ ...values, current: 1 } as P);
        } else {
          const values = formRef.current?.getFieldsValue() as P || {};
          await handleSearch(values);
        }
      },
      reloadAndRest: async () => {
        handleReset();
        await handleSearch({} as P);
      },
      onSearch: handleSearch,
      onReset: handleReset,
      onResetAndSearch: () => {
        handleReset();
        handleSearch({} as P);
      },
      clearSelected: () => {
        // 实现清除选中逻辑
      },
      startEditable: (rowKey: React.Key) => {
        stableRef.current.setEditableRowKeys([rowKey]);
      },
      cancelEditable: (rowKey: React.Key) => {
        handleCancel(rowKey);
      },
      search: handleSearch,
      updateData: stableRef.current.updateDataSource,
      setLoading: stableRef.current.setTableLoading,
    } as ExtendedActionType<P, T>;
  }, [handleSearch, handleReset, handleCancel]);

  // 初始化自动搜索
  useEffect(() => {
    if (autoSearch) {
      handleSearch({} as P);
    }
  }, [autoSearch, handleSearch]);

  const pageConfig: PcPageConfig<T> = {
    actionRef,
    formRef,
    formConfig,
    dataSource,
    loading,
    pagination,
    editableKeys: tableConfig.editableKeys || [],
    setEditableRowKeys,
    setTableLoading,
    updateDataSource,
    onSave,
    onCancel: handleCancel,
    createRecordTemplate,
  };

  return {
    pageRef: pageActionRef,
    pageConfig,
  };
};

export default usePcPage;
